package com.zb.service;

import com.alibaba.fastjson.JSON;
import com.zb.client.SkuFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>添加描述信息</p>
 *
 * @author 李柯
 * @since 2022年11月08日 15:45
 */
@Service
public class PageService {
    @Autowired
    private TemplateEngine templateEngine;

    @Value("${pagePath}")
    private String pagePath;

    @Autowired
    private SkuFeignClient skuFeignClient;

    public Map<String, Object> buildData(String skuId){
        Map<String,Object>info=skuFeignClient.info(skuId);
        Map<String,Object>spu=(Map<String, Object>) info.get("spu");
        String images=spu.get("images").toString();
        String [] strImg=images.split(",");
        info.put("imgs",strImg);
        String specItems=spu.get("specItems").toString();
        Map<String,String[]> specMap = JSON.parseObject(specItems, Map.class);
        info.put("specMap",specMap);
        return info;
    }


    public void createPage(String skuId){
        Context context = new Context();
        context.setVariables(buildData(skuId));
        File file=new File(pagePath);
        if (!file.exists()){
            file.mkdir();
        }
        File pageFile = new File(file, skuId + ".html");
        try {
            PrintWriter printWriter = new PrintWriter(pageFile, "UTF-8");
            templateEngine.process("item",context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
